package com.sanerzone.smscenter.biz.utils;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.sanerzone.common.support.sequence.MsgId;
import com.sanerzone.smscenter.biz.DataAccessCachImpl.DataAccessCachImpl;
import com.sanerzone.smscenter.biz.VerifyInterface.GatewayVerify;
import com.sanerzone.smscenter.biz.VerifyInterface.data.ResultData;
import com.sanerzone.smscenter.biz.VerifyInterface.impl.GatewayVerifyImpl;
import com.sanerzone.smscenter.biz.VerifyInterface.util.FilterUtil;
import com.sanerzone.smscenter.biz.cache.*;
import com.sanerzone.smscenter.biz.entity.SmsGateway;
import com.sanerzone.smscenter.biz.entity.SmsSubmitTemplate;
import com.sanerzone.smscenter.biz.entity.TopicQueue;
import com.sanerzone.smscenter.biz.iface.DataAccess.DataAccess;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSREQMessage;

/**
 * 通道匹配工具类
 * @author Administrator
 *
 */
public class GatewayHelper {

	private static   GatewayVerify gatewayVerify=new GatewayVerifyImpl();
	private static DataAccess dataAccess=new DataAccessCachImpl();
	/**
	 * 查找通道
	 * @param reqMeg  请求MQ
	 * @return
	 */
	public static List<SMSMTMessage> getGateway(SMSREQMessage reqMeg) {

		List<SMSMTMessage> result = Lists.newArrayList();
		if (reqMeg != null && StringHelper.isNotBlank( reqMeg.getPhones() )) {
			SMSMTMessage entity;
			String userid = reqMeg.getUserid();
			String accId = reqMeg.getAccId();

			String key = userid + "_" + accId;
			String content = reqMeg.getMsgContent();//短信内容
			String code = "T000"; //最开始设置成提交成功
			String templateId = reqMeg.getSmsContentId();//得到模板Id
			String phone = reqMeg.getPhones();
			entity = new SMSMTMessage();
			entity.setSmsREQMessage( reqMeg );
			entity.getSmsREQMessage().setPhones( "" );//把req的phones设置成空串
			entity.setId( new MsgId().toString() );//ID
			entity.setContentType( "0" );//内容类型 默认 0   0是什么意思？
			entity.setSmsContent( content );//短信内容

			entity.setPhone( phone );
			entity.setSmsContentSign( getSign( content ) );//短信签名
			entity.setServiceId( reqMeg.getCustomServiceid() ); //得到用户的短信类型

			FilterUtil.setSplit( phone,entity );


//			code = getPhoneOpt( entity );//获取号码属性
			//获得应是短信类型 1 2 3 验证码，通知，营销
			String accountGroupId = AccountCacheHelper.getStringValue( key, "serviceId", "" );
			String gwGroupId = AccountCacheHelper.getStringValue( key, "groupId", "" );
			//SmsGateway smsGateway = null;//最终要找的网关
			ResultData resultData = null;
			if ("T000".equals( code )) {//过滤一层签名
				resultData = gatewayVerify.verifySign( getSign( content ), userid ,dataAccess);//验证成功是T000  验证失败待审核V000

				if ("T000".equals( resultData.getCode() )) {
					//如果通过签名过滤，继续过滤下一层
					resultData = gatewayVerify.filterSensitiveWords( content ,dataAccess);
					if ("T000".equals( resultData.getCode() )) {
						//通过了敏感字，继续过滤黑名单
						resultData = gatewayVerify.filterBlackList( phone, accountGroupId, reqMeg,dataAccess );
						//将不合法订单也放入结果集中
						if (resultData.getSmsmtMessage() != null) {
							result.add( resultData.getSmsmtMessage() );

							phone=resultData.getPhoneStringAfterFilter();
							if (phone.equals( "" )){
								return result;
							}
							entity.setPhone( phone );
						}
						//限制该用户不能发送的运营商号码
						if ("T000".equals( resultData.getCode() )) {
							resultData=gatewayVerify.filterUserNotAllowedOprator( key,phone,reqMeg ,dataAccess);
							if (resultData.getSmsmtMessages().size()>0){
								//循环添加每一个衍生出来的订单
								for(SMSMTMessage smsmtMessage:resultData.getSmsmtMessages()){
									result.add( smsmtMessage );
								}
								phone=resultData.getPhoneStringAfterFilter();
								if (phone.equals( "" )){
									return result;
								}
								entity.setPhone( phone );

							}
							if ("T000".equals( resultData.getCode() )) {
								//最后找网关  真正找网关因为是分找到的多个网关，所以不返回，内部处理
								resultData = gatewayVerify.gateWayMatching( templateId, gwGroupId, entity, phone, reqMeg, result ,dataAccess);
//								if (resultData.getSmsGateway() == null) {
//									code = "D100";
//									resultData.setWaitReason( "未找到网关。" );
//								} else {
//									smsGateway = resultData.getSmsGateway();
//								}
								if (resultData.getCode()!=null&&resultData.getCode().startsWith( "V" )){
									code=resultData.getCode();
								}else{
									return resultData.getResult();
								}


							} else {
								code = resultData.getCode();
							}
						}
					} else {
						code = resultData.getCode();

					}
				} else {
					code = resultData.getCode();
				}
			}
			entity.setCheckReason( resultData.getCheckReason() );
			entity.setFailReason( resultData.getFailReason() );
			entity.setWaitReason( resultData.getWaitReason() );
			entity.setSendStatus( code );
			entity.setBizTime( new Date() );
			entity.setUpdateOrInsert( reqMeg.getInsertOrUpdate() );//获取到是更新还是插入
			entity.setSmsSize( (phone.split( "," ).length)*smsSize( content ) );//短信长度
			entity.setIsEffective( 1 );
			entity.setStatusChangeTime( new Date(  ) );
			FilterUtil.setNeedSplit( entity );

			if (phone.length()!=0){
				result.add( entity );
			}


		}
		return result;
	}
	
	//获取签名
	private static String getSign(String content){
		return SignHelper.get(content);
	}
	
	//获取手机号码属性(运营商+省市代码)
	private static String getPhoneOpt(SMSMTMessage entity){
		String phoneType = "";
		String cityCode = "";
		String code = "T000";
		if (entity.getPhone().length() > 12) {
			cityCode = "10";
			phoneType = "YD";
		} else {
			Map<String, String> phoneMap = PhoneHelper.get(entity.getPhone());
			if (phoneMap == null || phoneMap.size() == 0) {
				code = "F100";//号段匹配异常
			} else {
				phoneType = PhoneHelper.getPhoneType(phoneMap);//运营商
				cityCode = PhoneHelper.getCityCode(phoneMap);//省市代码

				if (StringHelper.isBlank(cityCode) || StringHelper.isBlank(phoneType)) {
					code = "F100";//号段匹配异常
				}
			}
		}
		entity.setPhoneArea(cityCode);
		entity.setPhoneType(phoneType);
		return code;

	}

	//过滤
	private static String filter(String key, String phone, String content){
		if (phone.length() > 12) {
			//过滤  黑名单 1：校验 0： 不校验
			int sysBlackListFlag = AccountCacheHelper.getIntegerValue(key, "sysBlackListFlag", 0);
			if (sysBlackListFlag == 1 && SysBlacklistHelper.isExist(phone))return "F101";//系统黑名单

			//过滤 营销黑名单
			int userBlackListFlag = AccountCacheHelper.getIntegerValue(key, "userBlackListFlag", 0);//营销黑名单
			if(userBlackListFlag == 1 && UserBlacklistHelper.isExist(key, phone))return "F102";//营销黑名单
		}
		//过滤敏感词
		int filterWordFlag = AccountCacheHelper.getIntegerValue(key, "filterWordFlag", 0);
		if(filterWordFlag == 1 && StringHelper.isNotBlank(KeywordsHelper.keywords(content)))return "F103";//包含敏感词
		return "V000";
	}
	
	public static int smsSize(String smsContent){
		return StringHelper.smsSize(smsContent);
	}
}
